package com.community.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.community.util.HttpRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.community.github.wxpay.sdk.WXPay;
import com.community.github.wxpay.sdk.WXPayUtil;
import com.community.github.wxpay.wx.MyConfig;


@Controller
public class WxController {

    /**
     * 微信小程序支付
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/doUnifiedOrder")
    @ResponseBody
    public Object doUnifiedOrder(@RequestParam String openid, int total_fee) throws Exception {
        System.out.println("openid：" + openid);
        System.out.println("total_fee：" + total_fee);
        Map<String, String> resultMap = new HashMap<String, String>();
        MyConfig config = null; //设置你的appid，商户号，支付秘钥
        WXPay wxpay = null;
        try {
            config = new MyConfig();
            wxpay = new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成32位随机数
        String nonce_str = WXPayUtil.generateNonceStr();
        //ip地址对象
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //ip地址
        String spbill_create_ip = addr.getHostAddress();
        //支付说明
        String body = "停车支付";
        //生成32位订单号
        String out_trade_no = WXPayUtil.generateNonceStr();

        //组装参数，用户生成统一下单接口的签名
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("appid", "***");//appid
        data.put("mch_id", "***");//商户号
        data.put("nonce_str", nonce_str);
        data.put("body", body);
        data.put("out_trade_no", out_trade_no);
        data.put("total_fee", String.valueOf(total_fee * 100));//支付金额
        data.put("spbill_create_ip", spbill_create_ip);
//        data.put("spbill_create_ip", "127.0.0.1");
        data.put("notify_url", "http://fc035418.ngrok.io/wxpay/wx/notify");//支付成功后的回调地址
        data.put("trade_type", "JSAPI");//支付类型
        data.put("openid", openid);//openid
        String sign = WXPayUtil.generateSignature(data, config.getKey());//第一次签名
        data.put("sign", sign);
        try {
            //把appid和mch_id封装进去,获取需要支付的4个参数
            Map<String, String> rMap = wxpay.unifiedOrder(data);
            System.out.println("用户生成统一下单接口的签名: " + rMap);
            String return_code = (String) rMap.get("return_code");
            String result_code = (String) rMap.get("result_code");
            String nonceStr = rMap.get("nonce_str");
            Long timeStamp = System.currentTimeMillis() / 1000;
            if ("SUCCESS".equals(return_code) && return_code.equals(result_code)) {
                String prepayid = rMap.get("prepay_id");
                resultMap.put("appId", "wxae9ae0f5f626fdd2");//appid
                //支付接口需要的参数
                resultMap.put("timeStamp", timeStamp + "");
                resultMap.put("nonceStr", nonceStr);
                resultMap.put("package", "prepay_id=" + prepayid);
                resultMap.put("signType", "MD5");
                //二次签名，第一次签名没用
                String sign2 = WXPayUtil.generateSignature(resultMap, config.getKey());
                resultMap.put("paySign", sign2);
                System.out.println("二次签名paySign : " + sign2);
                return resultMap;
            } else {
                return resultMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return resultMap;
        }
    }

    @RequestMapping("/testopenid")
    @ResponseBody
    public String getUserInfo(@RequestParam(name = "code") String code) throws Exception {
        System.out.println("code" + code);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid=wxd3a261a4f8553c4f";//自己的appid
        url += "&secret=c28eb0b99ab51e20f3a6761c2bb0929d";//自己的appSecret
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        url += "&connect_redirect=1";
        String res = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);    //GET方式
        CloseableHttpResponse response = null;
        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()          // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)                    // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)             // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)                    // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(false).build();           // 将上面的配置信息 运用到这个Get请求里
        httpget.setConfig(requestConfig);                         // 由客户端执行(发送)Get请求
        response = httpClient.execute(httpget);                   // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        System.out.println("响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            res = EntityUtils.toString(responseEntity);
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            System.out.println("响应内容为:" + res);
        }
        // 释放资源
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
        JSONObject jo = JSON.parseObject(res);
        String openid = jo.getString("openid");
        System.out.println("openid：" + openid);
        return openid;
    }

}
